import pandas as pd
import numpy as np

# 示例面板数据
data = pd.DataFrame({
    'ID': [1, 1, 1, 2, 2, 3, 3, 3],
    'Year': [2020, 2021, 2022, 2020, 2021, 2020, 2021, 2022],
    'State': ['A', 'B', 'B', 'B', 'A', 'C', 'B', 'A']
})

# 获取所有状态类别
states = sorted(data['State'].unique())
n_states = len(states)
state_dict = {s: i for i, s in enumerate(states)}

# 初始化计数矩阵
count_matrix = np.zeros((n_states, n_states))

# 按个体分组处理
for id_, group in data.groupby('ID'):
    group = group.sort_values('Year')
    states_sequence = group['State'].values
    print(states_sequence)
    for i in range(len(states_sequence) - 1):
        current = state_dict[states_sequence[i]]
        next_ = state_dict[states_sequence[i + 1]]
        count_matrix[current, next_] += 1
        print(count_matrix)
        print("```````````````````````")
    print("------------------------------------------------------")
for id_, group in data.groupby('ID'):
    group = group.sort_values('Year')
    states_sequence = group['State'].values

    for i in range(len(states_sequence) - 1):
        current = state_dict[states_sequence[i]]
        next_ = state_dict[states_sequence[i + 1]]
        count_matrix[current, next_] += 1


# 加1平滑处理
count_matrix += 1

# 计算转移概率
row_sums = count_matrix.sum(axis=1)
transition_matrix = count_matrix / row_sums[:, np.newaxis]

# 转换为DataFrame显示
pd.DataFrame(transition_matrix,
             index=states,
             columns=states,
             dtype=float)